﻿using Microsoft.Office.Interop.Word;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WordExcel
{
    public class NPOIWordHelper
    {
        public XWPFDocument wordDoc;
        public XWPFTable table;
        public XWPFParagraph paragraph;

        public NPOIWordHelper()
        {
            wordDoc = null;
            table = null;
            paragraph = null;
        }
        /// <summary>
        /// 打开WORD文档
        /// </summary>
        /// <param name="filePath"></param>
        public void OpenDocument(string filePath)
        {
            using(FileStream stream=new FileStream(filePath, FileMode.Open))
            {
                wordDoc = new XWPFDocument(stream);
            }
        }
        /// <summary>
        /// 新建WORD文档
        /// </summary>
        public void CreateDocument()
        {
            wordDoc = new XWPFDocument();
        }
        /// <summary>
        /// 获取WORD中的表格列表
        /// </summary>
        /// <returns></returns>
        public IList<XWPFTable> GetTables()
        {
            var result=  wordDoc.Tables;
            return result;
        }
        /// <summary>
        /// 返回指定表格
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public XWPFTable GetTable(int index)
        {
            if (index < wordDoc.Tables.Count)
            {
                var result = wordDoc.Tables[index];
                return result;
            }
            return null; 
        }
        /// <summary>
        /// 设置当前表格并返回结果
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public bool SetTable(int index)
        {
            bool result = false;
            if (index < wordDoc.Tables.Count)
            {
                table = GetTable(index);
                result = true;
            }
            return result;
        }

        /// <summary>
        /// 返回表格最大行数
        /// </summary>
        /// <returns></returns>
        public int GetMaxRowCount()
        {
            int maxRowCount = 0;
            if (table != null)
            {
                maxRowCount = table.Rows.Count;
            }
            return maxRowCount;
        }
        /// <summary>
        /// 判断单元格是否存在
        /// </summary>
        /// <param name="row"></param>
        /// <param name="colume"></param>
        /// <returns></returns>
        public bool IsExists(int row, int colume)
        {
            bool result = false;
            try
            {
                XWPFTableCell cell = table.GetRow(row).GetCell(colume);
                if (cell != null)
                {
                    result = true;
                }
            }catch(Exception ex)
            {

            }

            return result;
        }
        /// <summary>
        /// 获取单元格值
        /// </summary>
        /// <param name="row"></param>
        /// <param name="colume"></param>
        /// <returns></returns>
        public string GetCellValue(int row,int colume)
        {
            if (IsExists(row, colume))
            {
                var cell= table.GetRow(row).GetCell(colume);
               return cell.GetText();
            }
            return "";
        }
        /// <summary>
        /// 设置单元格值
        /// </summary>
        /// <param name="row"></param>
        /// <param name="colume"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetCellValue(int row,int colume,string value)
        {
            bool result = false;
            if (IsExists(row, colume))
            {
                var cell = table.GetRow(row).GetCell(colume);
                
               cell.SetText(value);
                result = true;
            }
            return result;
        }
        /// <summary>
        /// 设置单元格值
        /// </summary>
        /// <param name="row">行</param>
        /// <param name="colume">列</param>
        /// <param name="value">显示文本</param>
        /// <param name="fontFamily">字体</param>
        /// <param name="fontSize">字号</param>
        /// <param name="isBold">是否粗体</param>
        /// <param name="paIndex">替换行标</param>
        /// <param name="isRemoveOther">是否删除单元格内其他行</param>
        /// <returns></returns>
        public bool SetCellValue(int row, int colume, string value,string fontFamily,double fontSize,bool isBold, int paIndex = 0,bool isRemoveOther=true)
        {
            bool result = false;
            if (IsExists(row, colume))
            {
                var cell = table.GetRow(row).GetCell(colume);
                XWPFRun run=null;
                XWPFParagraph pa=null;
              
                if (cell.Paragraphs != null && cell.Paragraphs.Count()>0)
                {
                   
                    if(paIndex>0&& paIndex < cell.Paragraphs.Count)
                    {
                        pa = cell.Paragraphs[paIndex];
                    }else if (paIndex >= cell.Paragraphs.Count)
                    {
                        pa = cell.AddParagraph();
                    }
                    else 
                    {
                        pa = cell.Paragraphs.First(); 
                    } 
                }
                else
                {
                    pa = cell.AddParagraph();
                }
                if (isRemoveOther)
                {
                    var list = cell.Paragraphs.ToArray();
                    for(int i= list.Length-1; i>=0;i--)
                    {
                        if (cell.Paragraphs[i] != pa)
                        {
                            cell.RemoveParagraph(i);
                        }
                    }
                }
                if (pa.Runs != null && pa.Runs.Count > 0)
                {
                    run = pa.Runs[0];
                }
                else
                {
                    run = pa.CreateRun();
                }
                run.FontFamily = fontFamily;  // 设置字体  
                run.FontSize = fontSize;  // 设置字号  
                run.IsBold = isBold;
                run.SetText(value);

                result = true;
            }
            return result;
        }
        /// <summary>
        /// 获取段落列表
        /// </summary>
        /// <returns></returns>
        public IList<XWPFParagraph> GetParagraphs()
        {
           return wordDoc.Paragraphs;
        }
        /// <summary>
        /// 返回段落总数
        /// </summary>
        /// <returns></returns>
        public int GetParagraphCount()
        {
            return wordDoc.Paragraphs.Count;
        }
        /// <summary>
        /// 返回指定段落，并指定当前段落
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public XWPFParagraph GetParagraph(int index)
        {
            if (index >= 0 && index <= GetParagraphCount())
            {
                paragraph = wordDoc.Paragraphs[index];
                return paragraph;
            }
            return null;
        }
        /// <summary>
        /// 添加段落
        /// </summary>
        /// <returns></returns>
        public XWPFParagraph AddParagraph()
        {
            paragraph = wordDoc.CreateParagraph();
            return paragraph;
        }
        /// <summary>
        /// 添加段落
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public XWPFParagraph AddParagraph(string value)
        {
            paragraph = wordDoc.CreateParagraph();
            paragraph.CreateRun().SetText(value);
            
            return paragraph;
        }

        /// <summary>
        /// 返回指定段落的文本
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public string GetParagraphText(int index)
        {
            if (index >= 0 && index < GetParagraphCount())
            {
               return wordDoc.Paragraphs[index].Text;     
            }
            return "";
        }
        public void SetParagraphText(XWPFParagraph pa, string value)
        {
            pa.CreateRun().SetText(value);
        }

        public void CloseDocument()
        {
            if (wordDoc != null)
            {
                wordDoc.Close();
            }
         
        }
      

        /// <summary>
        /// 将工作簿保存至文件流。
        /// </summary>
        /// <param name="fileName">路径及文件名</param>
        /// <returns></returns>
        public bool SaveToFile(string fileName)
        {
            FileStream file = new FileStream(fileName, FileMode.Create);
            wordDoc.Write(file);
            file.Close();
            return true;
        }
        /// <summary>
        /// 将工作簿写入内存流中
        /// </summary>
        /// <returns></returns>
        public byte[] SaveToFileMemoryStream()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                wordDoc.Write(ms);
                var buffer = ms.GetBuffer();
                ms.Close();
                return buffer;
            }
        }
    }

}
